package io.gitee.hechenl.datamultitrans.mqtt;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

@Slf4j
public class MqttUtil {

    public static MqttConnectOptions createConnectOptions(
            boolean cleanSession,
            String username,
            String password) {
        MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setUserName(username);
        connOpts.setPassword(password.toCharArray());
        connOpts.setCleanSession(cleanSession);// 是否保留会话
        return connOpts;
    }

    public static MqttClient createClient(String clientId, String brokerUrl) throws MqttException {
        return new MqttClient(brokerUrl, clientId, new MemoryPersistence());
    }

    public static void publish(MqttClient client, String pubTopic, Integer qos, String content) throws MqttException {
        MqttMessage message = new MqttMessage(content.getBytes());
        message.setQos(qos);
        client.publish(pubTopic, message);
        log.info("Mqtt Message published");
    }

}
